package org.kunlong.netix.processor.standardprocessor;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.kunlong.netix.processor.standardprocessor.http.NetixRequest;
import org.kunlong.netix.processor.standardprocessor.http.NetixResponse;
import org.kunlong.netix.processor.standardprocessor.http.Response;
import org.kunlong.netix.processor.standardprocessor.http.StaticResourceProcessor;
import org.kunlong.netix.util.log.stringmanager.StringManager;

public class JobHandler implements Runnable {
	private static final String PACKAGE_NAME = JobHandler.class.getPackage()
			.getName();
	private static final Logger logger = Logger.getLogger(JobHandler.class);
	private static final String ERROR_IN_SLEEPING = "error_in_sleeping";
	private JobQueue jobQueue;
	private StaticResourceProcessor staticResourceProcessor = new StaticResourceProcessor();

	public JobHandler(JobQueue jobQueue) {
		// TODO Auto-generated constructor stub
		this.jobQueue = jobQueue;
	}

	public void run() {
		// TODO Auto-generated method stub
		while (true) {
			if (jobQueue.size() == 0) {
				synchronized (jobQueue) {// get the lock
					try {
						jobQueue.wait();// if there is no job, go to sleep
					} catch (Exception e) {
						// TODO: handle exception
						e.printStackTrace();
						String message = StringManager.getLogString(
								PACKAGE_NAME, ERROR_IN_SLEEPING);
						logger.error(message, e);
					}
				}
			}
			Job job = jobQueue.getJob();
			try {
				NetixRequest request = new NetixRequest(job.getS()
						.getInputStream());
				Response response = new NetixResponse(request, job.getS()
						.getOutputStream());
				request.setResponse(response);
				request.prase();
				staticResourceProcessor.process(request, response);
				response.finishResponse();
				job.getS().close();
			} catch (IOException e) {
				// TODO: handle exception
				e.printStackTrace();
				try {
					job.getS().close();
				} catch (IOException ioe) {
					// TODO: handle exception
					ioe.printStackTrace();
				}
			}
		}

	}

}
